<template>
   <div class="top">
      <van-swipe :autoplay="3000" lazy-render>
         <van-swipe-item v-for="image in images" :key="image">
            <img :src="image" />
         </van-swipe-item>
      </van-swipe>
   </div>
   <div>
      <van-field
      v-model="user.name"
      name="账号"
      label="账号"
      placeholder="账号"
      :rules="[{ required: true, message: '请填写账号' }]"
    />

     <van-field
      v-model="user.password"
      type="password"
      name="密码"
      label="密码"
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
   </div>

   <div>
      <van-button type="primary" @click="clickButton(1)" >登录</van-button>
      <van-button type="primary" @click="clickButton(2)">清空</van-button>
   </div>
   
</template>
<script lang = "ts">
//测试axios.ts
import { defineComponent ,reactive,getCurrentInstance} from 'vue'
export default defineComponent({
  name: 'test',
  setup() {
     //获取当前实例的对象
     const  {proxy}:any = getCurrentInstance()
     const  images = reactive( [
      'https://img.yzcdn.cn/vant/apple-1.jpg',
      'https://img.yzcdn.cn/vant/apple-2.jpg',
    ])
   
   //发送登陆请求的方法
    function toLogin() {
      proxy.$http
        .post(`/api/login`, {
          name: user.name,
          password: user.password,
        })
        .then((res: any) => {
          if (res.data.code == 0) {
            proxy.$toast.success("登陆成功");
            window.sessionStorage.setItem("token", res.data.data.token);

            proxy.$router.push({
              path: "home",
            });
          } else {
            proxy.$toast.fail("登陆失败");
          }
        })
        .catch((error: any) => {
          console.log(error);
        });
    }


    //登录对象
    const  user =  reactive({
       name:"",
       password:''
    })
   function clickButton<T>(value:number){
     if (value == 1) {
        if (user.name == "" && user.password == "") {
          proxy.$toast.fail("账号密码不能为空");
        } else {
          toLogin();
        }
      } else if (value == 2) {
        user.password = "";
        user.name = "";
      }
   }
    return  {
       images,
       user,
       clickButton,
       toLogin
    }
  }

})
</script>

<style scoped>
img{
   width:100%
}
.top{
   margin-bottom:3rem;
}
</style>
